import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/res/colors.dart';
import 'package:flutter_demo/res/resources.dart';
import 'package:flutter_demo/scene/pages/top_bar_widget.dart';
import 'package:flutter_demo/util/theme_utils.dart';
import 'package:flutter_demo/widgets/basic_card.dart';
import 'package:flutter_demo/widgets/my_scroll_bar.dart';
import 'package:flutter_demo/widgets/pull_load/list_state.dart';
import 'package:flutter_demo/widgets/pull_load/pull_load_widget.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';

class ScenePage extends StatefulWidget {
  ScenePage({Key key}) : super(key: key);

  @override
  _ScenePageState createState() => _ScenePageState();
}

class _ScenePageState extends State<ScenePage> 
    with AutomaticKeepAliveClientMixin<ScenePage>,ListState<ScenePage>,WidgetsBindingObserver{

  BuildContext _context;
  List<PostionInfoModel> postionCollectModel =[
    PostionInfoModel(posCode: '1-1-5',posName: '五一河绿岛生态公园桥-北',isCollect: true),
    PostionInfoModel(posCode: '1-1-5',posName: '五一河绿岛生态公园桥-南',isCollect: true),
  ];
  double _lastScrollPixels = 0;
  bool _isShowFloatingTopBar = false;
  double _topBarOpacity = 1;
  List myData = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20];
  
  
  @override
  void initState() {
    super.initState();
    FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
    WidgetsBinding.instance.addObserver(this);
    pullLoadWidgetControl.dataList = myData;
    setState(() {
      pullLoadWidgetControl.needLoadMore = false;
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    super.build(context);

    var pullLoadWidget = PullLoadWidget(
      control:pullLoadWidgetControl,
      itemBuilder:(BuildContext context,int index){
        switch(index){
          case 0:
            return Container(
              color:ThemeUtils.getBackgroundColor(context),
              child: TopBarWidget(
                topBarOpactiy: _topBarOpacity,
                actions: <Widget>[
                  IconButton(
                    icon: Icon(Icons.flip_to_front,color:Colors.white),
                    onPressed: (){},
                  )
                ],
              ),
            );
            break;
          case 1:
            return _buildCollectCard(context);
            break;
          case 2:
            return _buildPostionCard(context);
            break;
          case 3:
            return Container(
              child: ListView(
                primary: false,
                shrinkWrap: true,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test12'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test13'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test13'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test14'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test15'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test16'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test18'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test18'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test18'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test18'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test18'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test28'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test38'),),
                  ),
                  Container(
                    padding: EdgeInsets.all(15.0),
                    child: Center(child: Text('test20'),),
                  )
                ],
              ),
            );
            break;
          
        }
        return Container();
      },
      onRefresh:  handleRefresh,
      onLoadMore: onLoadMore,
      refreshKey: refreshIndicatorKey,
    );
    
    var body = Container(
      decoration: BoxDecoration(
        // gradient: Colours.primaryGradient,
      ),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: context, 
        child: NotificationListener<ScrollNotification>(
          onNotification: _onScroll,
          child: MyScrollbar(
            child:Stack(
              children: <Widget>[
                Container(
                  child: pullLoadWidget,
                ),
                Offstage(
                  offstage: !_isShowFloatingTopBar,
                  child: Container(
                    decoration: BoxDecoration(gradient:Colours.primaryGradient),
                    height: 48 + ScreenUtil.getStatusBarH(context),
                    width: ScreenUtil.getScreenW(context),
                    child: Column(
                      children: <Widget>[
                        SizedBox(
                          height: ScreenUtil.getStatusBarH(context),
                        ),
                        Container(
                          height:48.0,
                          child:_buildFloatingTopBar(),
                        )
                      ],
                    ),
                  ),
                )
              ],
            )
          ),
        )
      ),
    );
    
    return SafeArea(
      child: body,
      top:false,
    );
  }

  //收藏卡片
  Widget _buildCollectCard(BuildContext context){
    return 
    Padding(
      padding: const EdgeInsets.symmetric(horizontal: 0.0),
      child: BasicCard(
        leftTopTitle: '我的收藏',
        children: postionCollectModel.map<Widget>((item){
          return Column(
            children: <Widget>[
              ListTile(
                leading: null,
                title: Text(item.posName,style:TextStyle(fontSize: Dimens.font_sp16)),
                subtitle: Text('点位编号:${item.posCode}',style:TextStyle(fontSize: Dimens.font_sp12)),
                trailing: new Icon(Icons.keyboard_arrow_right),
              ),
              Divider(height: 1,color:Colours.line,),
            ],
          );
        }).toList()
      )
    );
  }
  // _buildListItem(PostionInfoModel item){
  //   return Row(
  //     mainAxisAlignment: MainAxisAlignment.start,
  //     children: <Widget>[
  //       Column(
  //         children: <Widget>[
  //           Text(item.posName,style:TextStyle(fontSize: Dimens.font_sp16)),
  //           Gaps.vGap10,
  //           Text(item.posCode,style:TextStyle(fontSize: Dimens.font_sp12))
  //         ],
  //       ),
  //       Icon(
  //         Icons.keyboard_arrow_right,
  //         size:25,
  //         color:Colours.text_gray
  //       ),
  //       Gaps.hGap20,
  //     ],
  //   );
  //   // return ListTile(
  //   //   leading: Gaps.empty,
  //   //   title: Text(item.posName,style:TextStyle(fontSize: Dimens.font_sp16)),
  //   //   subtitle: Text(item.posCode,style:TextStyle(fontSize: Dimens.font_sp12)),
  //   //   trailing: new Icon(Icons.keyboard_arrow_right),
  //   // );
  // }

  //附近及历史点位
  Widget _buildPostionCard(BuildContext context){
    return 
    Padding(
      padding: const EdgeInsets.symmetric(horizontal: 0.0),
      child: BasicCard(
        leftTopTitle: '附近点位',
        rightTopTitle:'更多'
      )
    );
  }

  @override
  Future<Null> onLoadMore() async {
     if(isLoading){
      return null;
    }
    isLoading = true;
    page++;
    //await doing 
    await getIndexListData(page);
    setState(() {
      pullLoadWidgetControl.needLoadMore = false;
    });
    isLoading = false;
  }

  getIndexListData(page) async {
    try {
      await Future.delayed(const Duration(seconds: 3));
      setState(() {
        pullLoadWidgetControl.dataList = myData;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Future<Null> handleRefresh() async {
    if(isLoading){
      return null;
    }
    isLoading = true;
    page =1;
    await getIndexListData(page); 
    setState(() {
      pullLoadWidgetControl.needLoadMore = false;
    });
    isLoading = false;
  }
  
  bool _onScroll(ScrollNotification scroll){
    //当前滑动距离
    double currentExtent = scroll.metrics.pixels;
    // double maxExtent = scroll.metrics.maxScrollExtent;

    //向下滚动
    if (currentExtent - _lastScrollPixels >0){
      if(currentExtent <=20){
        setState(() {
          double opacity = 1-currentExtent/20;
          _topBarOpacity = opacity>1 ?1:opacity;
        });
      }else{
        if(!_isShowFloatingTopBar){
          setState(() {
            _isShowFloatingTopBar = true;
          });
        }
      }
    }
    //向上滚动
    if (currentExtent - _lastScrollPixels <0){
      if(currentExtent <= 20){
        double opacity = 1 - currentExtent / 20;
        _topBarOpacity = opacity > 1 ? 1 : opacity;
        setState(() {
          _isShowFloatingTopBar = false;
        });
      }
    }
    _lastScrollPixels = currentExtent;
    return false;
  }

  Widget _buildFloatingTopBar(){
    return Stack(
      alignment: Alignment.centerLeft,
      children: <Widget>[
        Container(
          alignment: Alignment.centerLeft,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              GestureDetector(
                onTap: (){},
                child: Text(
                  '切换项目',
                  style:TextStyle(color:Colors.white)
                ),
              ),
              SizedBox(
                  width: 10,
              )
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left:15.0),
          child:Text('大丰区智慧技防项目',style:TextStyle(fontSize:Dimens.font_sp18,color:Colors.white,)),
        )
        
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;

  @override
  bool get isRefreshFirst => false;
}

//数据实体定义
class PostionInfoModel {
  final String posCode;
  final String posName;
  final double distance;
  final bool isCollect;

  PostionInfoModel({
    this.posCode,
    this.posName,
    this.distance,
    this.isCollect
  });
}